<template>
  <div class="zd-question wrap-table">

    <el-tabs v-model="userState" type="card">
      <el-tab-pane label="孕前期" name="1">
      </el-tab-pane>
      <el-tab-pane label="怀孕期" name="2">
      </el-tab-pane>
      <el-tab-pane label="儿童期-1" name="3">
      </el-tab-pane>
      <el-tab-pane label="儿童期-2" name="4">
      </el-tab-pane>
      <el-tab-pane label="儿童期-3" name="5">
      </el-tab-pane>
      <el-tab-pane label="儿童期-4" name="6">
      </el-tab-pane>
      <el-tab-pane label="儿童期-5" name="7">
      </el-tab-pane>
      <el-tab-pane label="儿童期-6" name="8">
      </el-tab-pane>
      <el-tab-pane label="儿童期-7" name="9">
      </el-tab-pane>
    </el-tabs>
    <!-- 查询区域 -->
    <el-form ref="form" :model="searchData" label-width="120px" class="clearfix">
      <!-- 操作区域 -->
      <div class="pull-left pd-bt">
        <el-button type="primary" @click="queryHandler" class=" pd-bt">添加</el-button>
      </div>
    </el-form>

    <!---->
    <template>
      <el-table :data="tableData" border empty-text="当前列表为空" v-loading="loading" element-loading-text="加载中" style="width: 100%">
        <el-table-column align="center" label="编号" width="70">
          <template slot-scope="scope">
            {{scope.row.RowId}}
          </template>
        </el-table-column>
        <el-table-column prop="BehaviorFrequency" label="a. 采取以下行为的频率" min-width="240">
        </el-table-column>
        <el-table-column prop="FrequencyValueType" :formatter="ValueFormater" align="center" label="分值" min-width="50">
        </el-table-column>
        <el-table-column prop="BehaviorImportance" label="b. 坚持这种行为的重要程度" min-width="240">
        </el-table-column>
        <el-table-column prop="ImportanceValueType" :formatter="ValueFormater" align="center" label="分值" min-width="50">
        </el-table-column>

        <el-table-column min-width="140" align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="changePositionHandler(1,scope.$index, scope.row)">
              <span class="arrow-top"></span>
            </el-button>
            <el-button size="small" type="text" @click="changePositionHandler(-1,scope.$index, scope.row)">
              <span class="arrow-bottom"></span>
            </el-button>
            <el-button size="small" type="text" @click="queryHandler(scope.$index, scope.row)">查看</el-button>
            <el-button size="small" type="text" @click="deleteHandler(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--分页-->
    <!-- <div class="block mg-20-auto"> -->
    <!-- <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pageId" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> -->
    <!-- </el-pagination> -->
    <!-- </div> -->

    <!-- 编辑查看对话框 -->
    <el-dialog title="添加/编辑问卷项描述" v-loading="loadingDialog" :close-on-click-modal="false" :append-to-body="true" top="0"
               :visible.sync="centerDialogVisible" width="60%">
        <div style="margin-right: 20px;overflow-x: hidden">
      <el-form :model="form" :rules="formRules" label-position="top" ref="questionForm">
        <el-form-item label="a. 采取以下行为的频率" :label-width="formLabelWidth" prop="BehaviorFrequency">
          <el-input v-model="form.BehaviorFrequency" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="频率答案列表">
          <el-input v-model="form.FrequencyRule1" auto-complete="off"
                    style="width: 100px;margin:0 10px 10px 0px" required="true"></el-input>
          <el-input v-model="form.FrequencyRule2" auto-complete="off"
                    style="width: 100px;margin:0 10px 10px 0px"></el-input>
          <el-input v-model="form.FrequencyRule3" auto-complete="off" style="width: 100px;margin:0 10px 10px 0px"></el-input>
          <el-input v-model="form.FrequencyRule4" auto-complete="off" style="width: 100px;margin:0 10px 10px 0px"></el-input>
          <el-input v-model="form.FrequencyRule5" auto-complete="off" style="width: 100px;margin:0 10px 10px 0px"></el-input>
        </el-form-item>
        <el-form-item label="分值规则" :label-width="formLabelWidth">
          <el-select v-model="form.FrequencyValueType" placeholder="请选择分值规则">
            <el-option label="1-5" value="1"></el-option>
            <el-option label="5-1" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="了解更多" :label-width="formLabelWidth" prop="FrequencyMore">
          <el-input type="textarea" v-model="form.FrequencyMore" auto-complete="off"></el-input>
        </el-form-item>

        <!-- 上传图片控件 -->
        <el-upload class="avatar-uploader" :auto-upload="false" action="" :show-file-list="false" :on-change="beforeAvatarUpload">
          <img v-if="form.FrequencyImage" :src="form.FrequencyImage" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-form-item label="b. 坚持这种行为的重要程度" :label-width="formLabelWidth" prop="BehaviorImportance">
          <el-input v-model="form.BehaviorImportance" auto-complete="off"></el-input>
        </el-form-item>

        <el-form-item label="分值规则 (一点都不重要) [1]----[2]----[3]----[4]----[5] (极其重要)" :label-width="formLabelWidth">
          <el-select v-model="form.ImportanceValueType" placeholder="请选择分值规则">
            <!-- <el-option v-for="(op,index) in tableData" :key="index" :label="op.title" :value="op.ID"></el-option> -->
            <el-option label="1-5" value="1"></el-option>
            <el-option label="5-1" value="2"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="了解更多" :label-width="formLabelWidth" prop="ImportanceMore">
          <el-input type="textarea" v-model="form.ImportanceMore" auto-complete="off"></el-input>
        </el-form-item>

        <!-- 上传图片控件 -->
        <el-upload class="avatar-uploader" :auto-upload="false" action="" :show-file-list="false" :on-change="beforeAvatarUpload1">
          <img v-if="form.ImportanceImage" :src="form.ImportanceImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

      </el-form>
        </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "question1",
  data() {
    return {
      searchData: {
        name: "",
        number: ""
      },
      form: {
        UserState: "", // 用户状态  1：孕前期，2：怀孕前
        BehaviorFrequency: "", /// 问题描述--频率
        FrequencyValueType: "", /// 频率分值排序规则 1:1-5，2：5-1
        FrequencyMore: "", /// 频率--了解更多
        FrequencyImage: "", // 频率图片，
        FrequencyImageSuffix: "", // 频率图片后缀
        BehaviorImportance: "", /// 问题描述--重要性
        ImportanceValueType: "", /// 重要性分值排序规则  1:1-5，2：5-1
        ImportanceMore: "", /// 重要性--了解更多
        ImportanceImage: "", // 重要性--图片
        ImportanceImageSuffix: "", /// 重要性--图片后缀
        SortIndex: 0 /// 排序
      },
      userState: "1", // 用户状态  1:孕前期日程模板，2：孕期日程模板
      formRules: {
        dictTypeName: [
          { required: true, message: "请填写地点名称", trigger: "blur" }
        ]
      },
      centerDialogVisible: false,
      formLabelWidth: "120px",
      total: null,
      pageSize: 10,
      pageId: 1,
      loading: false,
      loadingDialog: false,
      tableData: [],
      imageUrl: ""
    };
  },
  watch: {
    userState(value) {
      this.getList();
    }
  },
  mounted() {},
  methods: {
    ValueFormater(row, column, cellValue, index) {
      return cellValue ? (cellValue == 1 ? "1-5" : "5-1") : "";
    },
    beforeAvatarUpload(file, files) {
      let _this = this;

      if (file.raw.type !== "image/jpeg" && file.raw.type !== "image/png") {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
        return;
      }

      // 获取文件的后缀名
      this.form.FrequencyImageSuffix = file.name.split(".")[1];

      var reader = new FileReader();
      // reader.readAsDataURL(this.files[0]);
      reader.readAsDataURL(file.raw);
      reader.onload = function(e) {
        _this.$set(_this.form, "FrequencyImage", this.result);
      };

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },
    beforeAvatarUpload1(file) {
      let _this = this;

      if (file.raw.type !== "image/jpeg" && file.raw.type !== "image/png") {
        this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
        return;
      }

      // 获取文件的后缀名
      this.form.ImportanceImageSuffix = file.name.split(".")[1];

      let reader = new FileReader();
      reader.readAsDataURL(file.raw);

      // console.log(file)

      reader.onload = function(e) {
        _this.$set(_this.form, "ImportanceImage", this.result);
      };
    },
    changePositionHandler(direction, index, row) {
      // direction:1: 向上， -1 ： 向下；
      let tmpIndex;
      let tmpItem;

      if (direction == 1) {
        // 排在第一的不可以在向上
        if (index <= 0) {
          return;
        }
        // tmpIndex = index - 1;
        tmpIndex = row.RowId - 1;
        // tmpItem = this.tableData[tmpIndex];
        // if (!tmpItem) {
        //   tmpIndex = this.tableData.length - 1;
        //   tmpItem = this.tableData[tmpIndex];
        // }
      } else {
        // 排在最下面的不在刻意向下
        if (index >= this.tableData.length - 1) {
          return;
        }
        // tmpIndex = index + 1;
        tmpIndex = row.RowId + 1;
        // tmpItem = this.tableData[tmpIndex];
        // if (!tmpItem) {
        //   tmpIndex = 0;
        //   tmpItem = this.tableData[tmpIndex];
        // }
      }

      let that = this;
      row.SortIndex = tmpIndex;
      that.loading = true;
      // console.log(this.form);
      // debugger;
      that
        .service({
          url: "Dic/SaveQuestionnaireTemplateIndex",
          method: "post",
          data: {
            ...row
          }
        })
        .then(resp => {
          that.getList();
          // that.tableData.push(that.form);
          this.centerDialogVisible = false;
        })
        .catch(data => {
          that.getList();
          that.loading = false;
        });
      // this.tableData.splice(tmpIndex, 1, row);
      // this.tableData.splice(index, 1, tmpItem);
    },
    queryHandler(index, row) {
      console.log(row);
      // debugger;
      if (row) {
        this.form = JSON.parse(JSON.stringify(row));
        let picPrefix = "../../";
        if (this.form.FrequencyImage) {
          this.form.FrequencyImage = picPrefix + this.form.FrequencyImage;
        }

        if (this.form.ImportanceImage) {
          this.form.ImportanceImage = picPrefix + this.form.ImportanceImage;
        }
      } else {
        let obj = {
          UserState: "", // 用户状态  1：孕前期，2：怀孕前
          BehaviorFrequency: "", /// 问题描述--频率
          FrequencyValueType: "", /// 频率分值排序规则 1:1-5，2：5-1
          FrequencyMore: "", /// 频率--了解更多
          FrequencyImage: "", // 频率图片，
          FrequencyImageSuffix: "", // 频率图片后缀
          BehaviorImportance: "", /// 问题描述--重要性
          ImportanceValueType: "", /// 重要性分值排序规则  1:1-5，2：5-1
          ImportanceMore: "", /// 重要性--了解更多
          ImportanceImage: "", // 重要性--图片
          ImportanceImageSuffix: "" /// 重要性--图片后缀
        };

        this.form = JSON.parse(JSON.stringify(obj));

        // this.$nextTick(() => {
        //   this.$refs.questionForm.resetFields();
        // });
      }
      this.centerDialogVisible = true;
    },
    deleteHandler(index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let that = this;
          that
            .service({
              url: "Dic/DeleteQuestionnaireTemplate?sysId=" + row.SYS_ID,
              method: "post"
            })
            .then(resp => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });

              that.getList();
              // that.tableData.push(that.form);
            })
            .catch(data => {
              that.loading = false;
            });
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      //条数改变
      this.pageSize = val;
      this.getList();
    },
    handleCurrentChange(val) {
      //页数改变
      this.pageId = val;
      this.getList();
    },
    getList() {
      let that = this;
      that.loading = true;
      that
        .service({
          url: "Dic/GetQuestionnaireTemplate",
          method: "get",
          params: {
            userState: that.userState
          }
        })
        .then(response => {
          that.tableData = response.dtData;
          that.total = response.dtData.length || 0;
          that.loading = false;
        })
        .catch(data => {
          that.loading = false;
        });
    },
    searchHandler() {
      this.pageId = 1; // 分页索引
      this.getList();
    },
    saveHandler() {
      let that = this;
      this.loadingDialog = true;
      this.form.UserState = this.userState;
      let FrequencyImage = this.form.FrequencyImage
        ? this.form.FrequencyImage.replace(/data:image\/png;base64,/, "")
        : "";
      FrequencyImage = FrequencyImage.replace(/data:image\/jpeg;base64,/, "");
      this.form.FrequencyImage = FrequencyImage;

      let ImportanceImage = this.form.ImportanceImage
        ? this.form.ImportanceImage.replace(/data:image\/png;base64,/, "")
        : "";
      ImportanceImage = ImportanceImage.replace(/data:image\/jpeg;base64,/, "");
      this.form.ImportanceImage = ImportanceImage;
      // console.log(this.form);
      // debugger;
      that
        .service({
          url: "Dic/SaveQuestionnaireTemplate",
          method: "post",
          data: {
            ...that.form
          }
        })
        .then(resp => {
          that.getList();
          this.loadingDialog = false;
          // that.tableData.push(that.form);
          this.centerDialogVisible = false;
        })
        .catch(data => {
          that.getList();
          that.loading = false;
        });
    }
  },
  mounted() {
    this.getList();
  },
  components: {}
};
</script>
<style lang="scss">
.zd-question {
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 78px;
  height: 78px;
  line-height: 78px;
  text-align: center;
}
.avatar {
  width: 78px;
  height: 78px;
  display: block;
}

.arrow-top {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 1px 0 0 1px;
  transform: rotate(45deg) translateY(-50%);
  &::before {
    content: "";
    position: absolute;
    height: 1px;
    width: 12px;
    background-color: #409eff;
    left: 0;
    top: -1px;
    transform: rotate(45deg);
    transform-origin: 0 0;
  }
}

.arrow-bottom {
  position: relative;
  display: inline-block;
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border: 1px solid #409eff;
  border-width: 0 1px 1px 0;
  transform: rotate(45deg);
  &::before {
    content: "";
    position: absolute;
    height: 1px;
    width: 12px;
    background-color: #409eff;
    right: 0;
    bottom: 0;
    transform: rotate(45deg);
    transform-origin: 100% 0;
  }
}

.zd-question .el-dialog__wrapper .el-dialog .el-dialog__footer {
  text-align: center;
}
</style>